package com.ning.activitys.skysound.fragment.musicpavilion;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.ning.activitys.skysound.R;
import com.ning.activitys.skysound.activity.MainActivity;
import com.ning.activitys.skysound.base.BaseFragment;
import com.ning.activitys.skysound.base.MyApplication;
import com.ning.activitys.skysound.beans.GsonMusicList;
import com.ning.activitys.skysound.beans.NativeInformationBeans;
import com.ning.activitys.skysound.service.PlayService;
import com.ning.activitys.skysound.volley.VolleySingleton;

/**
 * Created by dllo on 16/1/8.
 */
public class MusicListFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    private MainActivity mainActivity;
    private ListView listView;
    private MusicListAdapter adapter;

    private GsonMusicList gsonMusicList;
    private Bundle bundle = new Bundle();

    private NativeInformationBeans nativeInformation = new NativeInformationBeans();
    private MyApplication myApplication;


    private String url = "http://218.200.160.29/rdp2/v5.5/" +
            "musicLists.do?&pageno=1&sort=2&groupcode=365925&tagid=-1&ua=Android_sst&version=4.2280";


    private String oldMusicUrl = "http://api.songlist.ttpod.com/songlists/303955957?app=ttpo" +
            "d&v=v8.1.4.2016011318&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2&active=1&net" +
            "=2&openudid=1320e380b9b2f879587531a841bd2709b0fe0b43&idfa=1797AE83-E11D-40E8-BF4A-51688F9D8197&utdi" +
            "d=VcqZd7Bai40DAKYNvRHg4TLh&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude=";
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mp_music_list,null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        listView = (ListView) view.findViewById(R.id.list_view_music_list_net);
        listView.setOnItemClickListener(this);

        myApplication = (MyApplication) mainActivity.getApplication();

        getData();
    }

    private void getData() {

        final Gson gson = new Gson();

        VolleySingleton.addRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                gsonMusicList = gson.fromJson(response,GsonMusicList.class);

                adapter = new MusicListAdapter();
                listView.setAdapter(adapter);

                /**
                 *  向数据库中存储
                 * */
                nativeInformation.setName("musicList");
                nativeInformation.setContent(response);

                try {
                    NativeInformationBeans nativeInformationBeans =
                            myApplication.dbUtils.findFirst(Selector.from(NativeInformationBeans.class).where("name","=","musicList"));

                    if (null == nativeInformationBeans) {

                        myApplication.dbUtils.save(nativeInformation);
                    }else {
                        myApplication.dbUtils.update(nativeInformation,"content");
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                try {

                    NativeInformationBeans nativeInformationBeans =
                            myApplication.dbUtils.findFirst(Selector.from(NativeInformationBeans.class).where("name","=","musicList"));

                    gsonMusicList = gson.fromJson(nativeInformationBeans.getContent(),GsonMusicList.class);

                    adapter = new MusicListAdapter();
                    listView.setAdapter(adapter);

                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     *  ListView 点击的Item 点击事件
     * */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        mainActivity.playService.setSkySoundListType(PlayService.MUSIC_LIST_TYPR);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        RankingDetailsFragment rankingDetailsFragment = RankingDetailsFragment.getInstance();


        bundle.putString("Url", oldMusicUrl);

        /**
         * 为什么不写  rankingDetailsFragment = null;
         * 此处会报错
         * */
        rankingDetailsFragment.setArguments(bundle);

        transaction.add(R.id.fragment_group_ranking_details, rankingDetailsFragment);
        transaction.commit();

    }


    public class MusicListAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return gsonMusicList.getList().size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            MyViewHolder myViewHolder;
            if (convertView == null){
                convertView = LayoutInflater.from(mainActivity).inflate(R.layout.item_music_list_net,parent,false);
                myViewHolder = new MyViewHolder(convertView);
                convertView.setTag(myViewHolder);
            }else {
                myViewHolder = (MyViewHolder) convertView.getTag();
            }
            VolleySingleton.getInstance().loadImage(myViewHolder.bigImage,gsonMusicList.getList().get(position).getImg());
            VolleySingleton.getInstance().loadImage(myViewHolder.iconImage,gsonMusicList.getList().get(position).getOwner().getIcon());

            myViewHolder.title.setText(gsonMusicList.getList().get(position).getTitle());
            myViewHolder.musicTag.setText(gsonMusicList.getList().get(position).getTagNames());
            myViewHolder.nicName.setText(gsonMusicList.getList().get(position).getOwner().getNickname());

            return convertView;
        }


        private class MyViewHolder{

            private NetworkImageView bigImage,iconImage;
            private TextView title,musicTag,nicName;

            public MyViewHolder(View view){

                bigImage = (NetworkImageView) view.findViewById(R.id.iv_image_music_list_net);
                iconImage = (NetworkImageView) view.findViewById(R.id.iv_icon_music_list_net);
                title = (TextView) view.findViewById(R.id.tv_title_music_list_net);
                musicTag = (TextView) view.findViewById(R.id.tv_tag_name_music_list_net);
                nicName = (TextView) view.findViewById(R.id.tv_nickname_music_list_net);
            }
        }
    }
}
